package com.bawei.module_mine.ui


import android.Manifest
import android.content.pm.PackageManager
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import android.os.Bundle

import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.lib_common.mvi.base.BaseMVIActivity
import com.bawei.module_mine.BaseApplication

import com.bawei.module_mine.R
import com.bawei.module_mine.common.ConstanstValue
import com.bawei.module_mine.common.UserUtils
import com.bawei.module_mine.databinding.ActivityOpenLiveBinding
import com.bawei.module_mine.rtmplive.Config
import com.bawei.module_mine.rtmplive.MediaPublisher
import com.bawei.module_mine.wiget.CustomGLSurfaceView
import javax.microedition.khronos.opengles.GL10
import org.json.JSONObject
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


@Route(path = "/module_mine/OpenLiveActivity")
class OpenLiveActivity : BaseMVIActivity() {
    lateinit var binding: ActivityOpenLiveBinding
    private var mMediaPublisher: MediaPublisher? = null
    private var isPublished = false

    /**
     * 聊天室名称
     */
    lateinit var roomName: String

    companion object {
        private const val CAMERA_PERMISSION_REQUEST_CODE = 1001
    }

    override fun generateViewModel() {}

    override fun getLayoutRootView(): View {
        binding = ActivityOpenLiveBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun handleState() {}

    private fun switchPublish() {
        if (isPublished) {
            stop()
        } else {
            start()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityOpenLiveBinding.inflate(layoutInflater)
        setContentView(binding.root)
        Log.d("OnlineCountPolling", "onCreate called")
        Log.d("OnlineCountPolling", "roomName=$roomName")
        // 定时轮询获取在线人数
        startOnlineCountPolling()
    }

    private var onlineCountTimer: java.util.Timer? = null
    private fun startOnlineCountPolling() {
        val roomId = roomName // 假设roomName就是roomId，实际请替换为你的roomId变量
        Log.d("OnlineCountPolling", "startOnlineCountPolling() called, roomId=$roomId")
        onlineCountTimer?.cancel()
        onlineCountTimer = java.util.Timer()
        onlineCountTimer?.schedule(object : java.util.TimerTask() {
            override fun run() {
                Log.d("OnlineCountPolling", "轮询请求在线人数，roomId=$roomId")
                fetchOnlineCount(roomId)
            }
        }, 0, 3000) // 每3秒请求一次
    }

    private fun fetchOnlineCount(roomId: String) {
        Log.d("OnlineCountPolling", "fetchOnlineCount called, roomId=$roomId")
        runOnUiThread {
            GlobalScope.launch(Dispatchers.Main) {
                try {
                    val api = com.bawei.lib_net.RetrofitFactory.getRetrofitFactory().create(
                        com.bawei.module_live.version2.mvi.model.api.LiveApi::class.java
                    )
                    val response = api.getLiveRoomUsers(roomId)
                    val count = response.data?.size ?: 0
                    Log.d("OnlineCountPolling", "获取到在线人数: $count，roomId=$roomId")
                    binding.onlineCount.text = count.toString()
                } catch (e: Exception) {
                    Log.e("OnlineCountPolling", "获取在线人数失败: ${e.message}")
                    binding.onlineCount.text = "0"
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        binding.glsvLiveLivepublish.onResume()
        // 检查摄像头权限
        if (checkCameraPermission()) {
            checkDeviceSupport()
            initCamera()
        }
    }

    private fun checkCameraPermission(): Boolean {
        val permission = Manifest.permission.CAMERA
        return if (ContextCompat.checkSelfPermission(
                this,
                permission
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            true
        } else {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(permission),
                CAMERA_PERMISSION_REQUEST_CODE
            )
            false
        }
    }

    private fun checkDeviceSupport() {
        val pm = packageManager
        if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) {
            Toast.makeText(this, "该设备不支持摄像头", Toast.LENGTH_LONG).show()
            finish()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                initCamera()
            } else {
                Toast.makeText(this, "需要摄像头权限才能开启直播", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun initCamera() {
        try {
            mMediaPublisher = MediaPublisher.newInstance(
                Config.Builder()
                    .setFps(30)
                    .setMaxWidth(720)
                    .setMinWidth(320)
                    .setUrl("rtmp://58.200.131.2:1935/livetv/cctv1")
                    .build()
            )
            mMediaPublisher?.init()

            binding.glsvLiveLivepublish?.setCallback(object :
                CustomGLSurfaceView.OnSurfaceCallback {
                override fun surfaceCreated() {
                    try {
                        mMediaPublisher?.initVideoGatherer(
                            this@OpenLiveActivity,
                            binding.glsvLiveLivepublish.surfaceTexture
                        )
                    } catch (e: Exception) {
                        Log.e("OpenLiveActivity", "初始化视频采集器失败", e)
                        Toast.makeText(
                            this@OpenLiveActivity,
                            "无法初始化摄像头，请检查设备或重试",
                            Toast.LENGTH_LONG
                        ).show()
                    }
                }

                override fun surfaceChanged(gl: GL10?, width: Int, height: Int) {
                    mMediaPublisher?.initVideoGatherer(
                        this@OpenLiveActivity,
                        binding.glsvLiveLivepublish.surfaceTexture
                    )
                }
            })

            binding.ivLivePublishStartLive.setOnClickListener {
                val ws = BaseApplication.getWS()
                if (ws != null) {
                    ws.sendMsg(ConstanstValue.LIVE_FLAG + ConstanstValue.SPLITFLAG + UserUtils.getCurrentUserJson() + ConstanstValue.SPLITFLAG + roomName)
                    if (!flag) {
                        isPublished = false
                        binding.ivLivePublishStartLive.setImageDrawable(resources.getDrawable(R.drawable.ic_live_stoplive))
                    } else {
                        isPublished = true
                        binding.ivLivePublishStartLive.setImageDrawable(resources.getDrawable(R.drawable.ic_live_startlive))
                    }
                    switchPublish()
                    flag = !flag
                } else {
                    Toast.makeText(this, "WebSocket 尚未初始化，请先连接", Toast.LENGTH_SHORT).show()
                    Log.e("OpenLiveActivity", "WebSocket is null when trying to send message")
                }
            }
            binding.ivLiveBack.setOnClickListener {
                closeThis()
            }
        } catch (e: Exception) {
            Log.e("OpenLiveActivity", "初始化摄像头失败", e)
            Toast.makeText(this, "无法打开摄像头，请确保没有被其他应用占用", Toast.LENGTH_LONG)
                .show()
        }
    }

    var flag: Boolean = false

    private fun start() {
        try {
            mMediaPublisher!!.initAudioGatherer()
            mMediaPublisher!!.initEncoders()
            mMediaPublisher!!.starPublish()
            mMediaPublisher!!.startGather()
            mMediaPublisher!!.startEncoder()
            isPublished = true
        } catch (e: Exception) {
            Log.e("OpenLiveActivity", "启动推流失败", e)
            Toast.makeText(this, "推流启动失败", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onPause() {
        super.onPause()
        binding.glsvLiveLivepublish.onPause()
        stop()
    }

    private fun stop() {
        mMediaPublisher?.stopPublish()
        mMediaPublisher?.stopGather()
        mMediaPublisher?.stopEncoder()
        isPublished = false
    }

    override fun onDestroy() {
        super.onDestroy()
        // 释放摄像头资源
        binding.glsvLiveLivepublish.releaseCamera()
        mMediaPublisher?.release()
        // 停止轮询
        onlineCountTimer?.cancel()
    }
}